package com.nokia.ion.sdu.cdr_decoder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;

public class Functions {

	public static byte[] readBytes(InputStream is, int len) throws IOException {
		byte[] b = new byte[len];
		int rd = 0;
		int t = 0;
		while (rd < len) {
			t = is.read(b, rd, len - rd);
			if (t < 0) {
				throw new IOException("" + len + " bytes expected, " + rd + " bytes got.");
			}
			rd = rd + t;
		}
		return b;
	}

	public static int readAsnTag(InputStream is) throws IOException {
		byte[] first = Functions.readBytes(is, 1);
		int tagValue = first[0] & 0x1F;
		if (tagValue != 0x1F) return tagValue;
		
		tagValue = 0;
		
		byte[] next;
		boolean hasMore;

		do {
			next = Functions.readBytes(is, 1);
			hasMore = (next[0] & 0x80) > 0;
			tagValue = (tagValue << 7) + (next[0] & 0x7F);
		} while (hasMore);
		
		return tagValue;
	}

	public static int readAsnLen(InputStream is) throws IOException {
		int lenValue;
		byte[] next = Functions.readBytes(is, 1);

		if ((next[0] & 0x80) > 0) {
			int len = next[0] & 0x7F;
			next = Functions.readBytes(is, len);
			lenValue = Functions.toInt(next);
		} else {
			lenValue = next[0] & 0x7F;
		}
		return lenValue;
	}

	public static int toInt(byte[] b) {
	    int i = 0;
	    if (0 < b.length) {
	    	i |= b[0] & 0xFF;
	    }
	    if (1 < b.length) {
	    	i <<= 8;
	    	i |= b[1] & 0xFF;
	    }
	    if (2 < b.length) {
	    	i <<= 8;
	    	i |= b[2] & 0xFF;
	    }
	    if (3 < b.length) {
	    	i <<= 8;
	    	i |= b[3] & 0xFF;
	    }
	    return i;
	}

	public static String toHexString(byte[] b) {
//		String result = "0x";
		StringBuilder sb = new StringBuilder(40);
		for (int i = 0; i < b.length; i++) {
//			result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
			sb.append(Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ));
		}
		return sb.toString();
	}
	
	public static long toLong(byte[] b) {
		long l = 0;
		l |= b[0] & 0xFF;
		for (int i = 1; i < b.length; i++) {
			l <<= 8;
			l |= b[i] & 0xFF;
		}
		return l;
	}

	public static String toIPAddress(byte[] buf, int p) {
		String ret = "";
		for (int i = 0; i < 4; i++) {
			int v = buf[p + i];
			if (v < 0) v += 256;
			if (i != 3) ret = ret + v + ".";
			else ret = ret + v;
		}
		return ret;
	}

	public static Date timestampToDate(String ts) {
		int year = Integer.parseInt(ts.substring(0, 2)) + 2000;
		int month = Integer.parseInt(ts.substring(2, 4)) - 1;
		int day = Integer.parseInt(ts.substring(4, 6));
		int hour = Integer.parseInt(ts.substring(6, 8));
		int minute = Integer.parseInt(ts.substring(8, 10));
		int second = Integer.parseInt(ts.substring(10, 12));

		Calendar c = Calendar.getInstance();
		c.set(year, month, day, hour, minute, second);
		return c.getTime();
	}
}
